// +----------------------------------------------------------------------
// | CmsWing [ 美业管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 psi All rights reserved.
// +----------------------------------------------------------------------
// | Author: huang <2374266244@qq.com>
// +----------------------------------------------------------------------
'use strict';
import Base from './base.js';

/**
*开单页面控制器
*/
export default class extends Base {
  async orderlistAction() {
    const filter = JSON.parse(this.get('filter'));
    const where = {
      'o.departmentid': this.shop_userinfo.departmentid,
      'o.ordertype': 2,
      's.name|s.vipcard|s.phone|a.name|oa.name|o.order_sn': ['like', '%' + filter.search + '%']
    };
    if (filter.status != 0) {
      where['o.status'] = filter.status - 1;
    }

    if (filter.times && (filter.times[0] != null && filter.times[1] != null)) {
      const begintime = Math.floor(new Date(filter.times[0]).setHours(0, 0, 0, 0) / 1000);
      const endtime = Math.floor(new Date(filter.times[1]).setHours(0, 0, 0, 0) / 1000) + 86400;
      where['o.addtime'] = {'>=': begintime, '<': endtime};
    }
    const list = await this.model('or_shop_order')
      .alias('o')
      .field('o.id, d.name as shopname, s.name as gname,s.phone as gphone,s.vipcard,o.order_sn,o.consumemoney,o.recemoney,o.usebalance,o.usegiftbalance,o.addtime,o.operatorid,o.auditorid,o.status, a.name as operatorname, oa.name as auditorname, o.cardreduce, o.guestid')
      .join('`think_or_guest` s on s.id = o.guestid')
      .join('`think_or_department` d on s.departmentid = d.id')
      .join('`think_or_admin` a on a.id = o.operatorid')
      .join('`think_or_admin` oa on oa.id = o.auditorid')
      .where(where)
      .page(filter.currentSize, filter.pageSize)
      .order('o.addtime desc')
      .countSelect();

    return this.json(list);
  }

  /*
   * 新开单把散客和老客合并在一起方便后期维护
   * @author: huang
   */
  async newopenorderAction() {
    const data = JSON.parse(this.post('data'));
    // 先查看订单是否已经被删除或者已经结账
    if (data.order.id) {
      const order = await this.model('or_shop_order').where({id: data.order.id}).find();
      if (!order || order.status != 0) {
        return this.fail('该订单不存在或者已经结账！');
      }
    }
    // 制作订单数据表
    const orderdata = {
      order_sn: data.order.order_sn ? data.order.order_sn : await this.getordersn('LSD', 1),
      guestid: data.ginfo.id,
      departmentid: this.shop_userinfo.departmentid,
      operatorid: this.shop_userinfo.id,
      addtime: Math.round(Date.parse(new Date()) / 1000),
      remarks: data.order.remarks,
      recemoney: data.order.usemoney,
      cardreduce: data.order.usecard,
      usebalance: data.order.usebalance,
      usegiftbalance: data.order.usegiftbalance,
      ordertype: 2,
      iscross: data.order.crossShop
    };
    const model = this.model('or_shop_order');
    await model.transaction(async() => {
      try {
        // 要写入的表有，order，orderinfo，有暂存写到暂存表
        let resorder = 1;
        if (data.order.id) {
          delete orderdata.addtime;
          resorder = await model.where({id: data.order.id}).update(orderdata);
        } else {
          resorder = await model.add(orderdata);
        }
        const orderinfodata = [];
        const orderUserList = [];
        data.orderlist.forEach((row, index) => {
          orderinfodata.push({
            departmentid: this.shop_userinfo.departmentid,
            orderid: data.order.id ? data.order.id : resorder,
            consumetype: row.consumetype,
            type: row.type,
            typeid: row.typeid,
            typename: row.typename,
            guestcardid: row.guestcardid ? row.guestcardid : 0,
            guestcardinfoid: row.guestcardinfoid ? row.guestcardinfoid : 0,
            num: row.num,
            price: row.price,
            totalprice: (row.price * row.num).toFixed(2),
            discount: row.discount,
            amount: row.amount,
            usemoney: row.usemoney,
            usebalance: row.usebalance,
            usegiftbalance: row.usegiftbalance,
            usecard: row.usecard,
            istemp: row.istemp ? 1 : 0,
            isgift: row.isgift ? 1 : 0,
            brandid: row.brandid,
            tempid: row.tempid ? row.tempid : 0,
            lineindex: index + 1
            // cost: row.cost
          });
          if (row.userTypeList.length > 0) {
            row.userTypeList.forEach((rows) => {
              rows.userFenList.forEach((fenList) => {
                if (fenList.percent > 0) {
                  orderUserList.push({
                    orderid: data.order.id ? data.order.id : resorder,
                    lineindex: index + 1,
                    classid: rows.subjectchildclassid,
                    userid: fenList.id,
                    fuwutype: rows.fuwutype || 0,
                    percent: fenList.percent
                  });
                }
              });
            });
          }
        });
        let resdelorderinfo = 1;
        let resdeluesrlist = 1;
        if (data.order.id) {
          resdelorderinfo = await this.model('or_shop_orderinfo').db(model.db()).where({orderid: data.order.id}).delete(); // 删除老数据
          resdeluesrlist = await this.model('or_shop_orderuserlist').db(model.db()).where({orderid: data.order.id}).delete(); // 删除老数据
        }
        // 更新客户备注（这个暂时不放在回滚里面删除订单时无法退回）
        if (data.ginfo.id != 1 && data.ginfo.id != 2) {
          await this.model('or_guest').db(model.db()).where({id: data.ginfo.id}).update({remarks: data.ginfo.remarks});
        }
        const resorderinfo = await this.model('or_shop_orderinfo').db(model.db()).addMany(orderinfodata);
        let resorderuserlist = 1;
        if (orderUserList.length) {
          resorderuserlist = await this.model('or_shop_orderuserlist').db(model.db()).addMany(orderUserList);
        }
        /* console.log(resorder);
        console.log(resorderinfo);
        console.log(resdelorderinfo);
        console.log(resorderuserlist);
        console.log(resdeluesrlist); */
        if (resorder && resorderinfo && resdelorderinfo && resorderuserlist && resdeluesrlist !== false) {
          await model.commit();
          return this.success({id: data.order.id ? data.order.id : resorder, info: '操作成功！'});
        } else {
          await model.rollback();
          return this.fail('操作失败！');
        }
      } catch (e) {
        console.log(e);
        await model.rollback();
        return this.fail('操作失败！');
      }
    });
  }

  /**
   * 删除订单
   * @author：黄
   */
  async deleteorderAction() {
    const id = this.post('id');

    // 判断是否可以删除
    const order = await this.model('or_shop_order').where({id: id}).find();
    if (!order || order.status != 0) {
      return this.fail('该订单不存在或者已经结账！');
    }
    // 删除操作
    const model = this.model('or_shop_order');
    await model.transaction(async() => {
      try {
        const ores = await model.where({id: id}).delete();
        const gres = await this.model('or_shop_orderinfo').db(model.db()).where({orderid: id}).delete();
        const ures = await this.model('or_shop_orderuserlist').db(model.db()).where({orderid: id}).delete();
        if (ores && gres && ures !== false) {
          await model.commit();
          return this.success({data: 200, info: '删除成功！'});
        } else {
          await model.rollback();
          return this.fail('删除失败！');
        }
      } catch (e) {
        await model.rollback();
        return this.fail('删除失败！');
      }
    });
  }

  /**
   * 付款结账功能
   * @author：黄
   */
  async jiezhangAction() {
    // 获取需要的数据
    const data = JSON.parse(this.post('data'));
    const orderinfo = await this.model('or_shop_order').where({id: data.order.id}).find();
    const nowtime = orderinfo.addtime;
    const orderlist = await this.model('or_shop_orderinfo')
      .alias('o')
      .field('o.*, s.nownum, t.nownum as tnownum, s.isdisabled, t.isdisabled as goodsdisabled')
      .join('left join `think_or_shop_guestcardsubject` s on o.guestcardinfoid = s.id')
      .join('left join `think_or_shop_guest_temp_reserve` t on o.tempid = t.id')
      .where({'o.orderid': data.order.id})
      .select();
    const shop_id = this.shop_userinfo.departmentid;
    const addtime = Math.round(new Date().getTime() / 1000);

    /**
      *过账前的判断
      *判断是否结账  前置
      *判断商品库存是否足够 后置
      *判断用户卡项是否足够充值卡判断余额、期卡判断日期、次卡判断次数 后置
      *判断暂存商品或项目是否存在 后置
      *判断银行卡是否可用 后置
      *判断账户余额和赠送金额是否足够 后置
      */

    // 判断当前订单是否已经结账
    if (orderinfo.status !== 0) {
      return this.fail('订单已结账');
    }

    const isCanEditOrder = await this.isCanEditOrder(orderinfo.id, 'LSD');
    if (!isCanEditOrder) {
      return this.fail('暂不允许操作其他店单据！');
    }

    // 确定发放月份
    const unix = new Date(orderinfo.addtime * 1000);
    const nYear = unix.getFullYear();
    let nMonth = unix.getMonth() + 1;
    nMonth = nMonth < 10 ? '0' + nMonth : nMonth;
    const jiesuandate = nYear + '' + nMonth;

    // 事务开启
    const guestModel = this.model('or_shop_order');
    await guestModel.transaction(async() => {
      try {
        let resxianjin = 1;
        let resorder = 1;
        let resreduce = 1;
        let resyeji = 1;
        let baseInfo = 1;
        // 现金业绩表
        // 重新规划业绩分配，暂时用两种方式
        if (data.yejilist.length > 0) {
          const yejidata = [];
          const selluserList = [];
          const reduceuserList = [];
          const basepay = [];

          for (let i = 0; i < data.yejilist.length; i++) {
            const isfafang = await this.model('or_shop_usergongzi').db(guestModel.db()).where({userid: data.yejilist[i].userid, jiesuandate: jiesuandate}).find();
            if (!think.isEmpty(isfafang)) {
              await guestModel.rollback();
              return this.fail('有员工工资已经审核不能再分配');
            }
            yejidata.push({
              shopid: shop_id,
              orderid: data.order.id,
              ordertype: 'LSD',
              xianjinyeji: data.yejilist[i].xianjinyeji || 0,
              kahaoyeji: data.yejilist[i].kahaoyeji || 0,
              xianjinticheng: data.yejilist[i].xianjinticheng || 0,
              kahaoticheng: data.yejilist[i].kahaoticheng || 0,
              qitaticheng: data.yejilist[i].qitaticheng || 0,
              xianjinjieti: data.yejilist[i].xianjinjieti || 0,
              kahaojieti: data.yejilist[i].kahaojieti || 0,
              userid: data.yejilist[i].userid,
              bumenid: data.yejilist[i].bumenid,
              xiaozuid: data.yejilist[i].xiaozuid,
              guestid: data.order.guestid,
              addtype: data.yejilist[i].addtype || 0,
              addtime: nowtime
            });
            if (data.yejilist[i].xianjinyeji > 0) {
              selluserList.push({
                orderid: data.order.id,
                feattype: 'LSD',
                shopid: shop_id,
                feat: data.yejilist[i].xianjinyeji,
                userid: data.yejilist[i].userid,
                bumenid: data.yejilist[i].bumenid,
                xiaozuid: data.yejilist[i].xiaozuid,
                guestid: data.order.guestid,
                addtime: nowtime
              });
            }
            if (data.yejilist[i].kahaoyeji > 0) {
              reduceuserList.push({
                orderid: data.order.id,
                feattype: 'LSD',
                shopid: shop_id,
                feat: data.yejilist[i].kahaoyeji,
                userid: data.yejilist[i].userid,
                bumenid: data.yejilist[i].bumenid,
                xiaozuid: data.yejilist[i].xiaozuid,
                guestid: data.order.guestid,
                addtime: nowtime
              });
            }
            if (data.yejilist[i].xianjinticheng > 0) {
              basepay.push({
                userid: data.yejilist[i].userid,
                category: 2,
                type: 1,
                money: data.yejilist[i].xianjinticheng,
                orderid: data.order.id,
                ordertype: 2,
                addtime: addtime,
                time: orderinfo.addtime
              });
            }
            if (data.yejilist[i].kahaoticheng > 0) {
              basepay.push({
                userid: data.yejilist[i].userid,
                category: 2,
                type: 3,
                money: data.yejilist[i].kahaoticheng,
                orderid: data.order.id,
                ordertype: 2,
                addtime: addtime,
                time: orderinfo.addtime
              });
            }
            if (data.yejilist[i].shougongticheng > 0) {
              basepay.push({
                userid: data.yejilist[i].userid,
                category: 2,
                type: 2,
                money: data.yejilist[i].shougongticheng,
                orderid: data.order.id,
                ordertype: 2,
                addtime: addtime,
                time: orderinfo.addtime
              });
            }
            if (data.yejilist[i].qitaticheng > 0) {
              basepay.push({
                userid: data.yejilist[i].userid,
                category: 2,
                type: 4,
                money: data.yejilist[i].qitaticheng,
                orderid: data.order.id,
                ordertype: 2,
                addtime: addtime,
                time: orderinfo.addtime
              });
            }
            if (data.yejilist[i].xianjinjieti > 0) {
              basepay.push({
                userid: data.yejilist[i].userid,
                category: 2,
                type: 5,
                money: data.yejilist[i].xianjinjieti,
                orderid: data.order.id,
                ordertype: 2,
                addtime: addtime,
                time: orderinfo.addtime
              });
            }
            if (data.yejilist[i].kahaojieti > 0) {
              basepay.push({
                userid: data.yejilist[i].userid,
                category: 2,
                type: 6,
                money: data.yejilist[i].kahaojieti,
                orderid: data.order.id,
                ordertype: 2,
                addtime: addtime,
                time: orderinfo.addtime
              });
            }
          }

          if (selluserList.length > 0) {
            resxianjin = await this.model('or_shop_yejixianjin').db(guestModel.db()).addMany(selluserList);
          }
          if (reduceuserList.length > 0) {
            resreduce = await this.model('or_shop_yejicardreduce').db(guestModel.db()).addMany(reduceuserList);
          }
          resyeji = await this.model('or_shop_yejiticheng').db(guestModel.db()).addMany(yejidata);
          baseInfo = basepay.length > 0 ? await this.model('or_shop_userbasepay').db(guestModel.db()).addMany(basepay) : 1;
        }

        const orderdata = {
          status: 1,
          auditorid: this.shop_userinfo.id,
          gendanid: data.order.gendanid
        };

        // 更改操作客户的余额和写入账户金额
        // 判断是否使用客户的余额，如果使用更改客户的余额信息，并且写入客户余额变动日志

        const ginfo = await this.model('or_guest').db(guestModel.db()).where({id: data.order.guestid}).find();
        let ginfodata = {arrivetime: nowtime}, ginfodatalog = {}, accountdata = [], accountdatalog = [];
        if (data.order.usebalance > 0 || data.order.usegiftbalance > 0) {
          if (ginfo.giftbalance - data.order.usegiftbalance < 0) {
            await guestModel.rollback();
            return this.fail('该客户赠送余额不足以支付当前订单！');
          }
          ginfodata = Object.assign(ginfodata, {balance: ginfo.balance - data.order.usebalance, giftbalance: ginfo.giftbalance - data.order.usegiftbalance});
          ginfodatalog = {
            guestid: data.order.guestid,
            shopid: shop_id,
            ordertype: 'LSD',
            orderid: data.order.id,
            balance: -1 * data.order.usebalance,
            giftbalance: -1 * data.order.usegiftbalance,
            addtime: nowtime,
            type: 3
          };
        }
        for (var i = data.paylist.length - 1; i >= 0; i--) {
          // 普通收款
          if (data.paylist[i].type == 1) {
            const account = await this.model('or_shop_account').db(guestModel.db()).where({id: data.paylist[i].accountid}).find();
            account.balance += Number(data.paylist[i].paymoney);
            accountdata.push(account);
            accountdatalog.push({
              departmentid: shop_id,
              accountid: data.paylist[i].accountid,
              ordertype: 'LSD',
              type: 1,
              orderid: data.order.id,
              money: data.paylist[i].paymoney,
              addtime: nowtime
            });
          }
        };

        let resginfo = 1, resginfolog = 1, resaccount = 1, resaccountlog = 1;
        resginfo = await this.model('or_guest').db(guestModel.db()).where({id: data.order.guestid}).update(ginfodata);
        if (!think.isEmpty(ginfodatalog)) {
          resginfolog = await this.model('or_shop_guest_accountlog').db(guestModel.db()).add(ginfodatalog);
        }

        if (accountdata.length > 0) {
          resaccount = await this.model('or_shop_account').db(guestModel.db()).updateMany(accountdata);
          resaccountlog = await this.model('or_shop_accountlog').db(guestModel.db()).addMany(accountdatalog);
        }

        // 开始判断客户卡项信息并且减去相应的卡信息
        const goodsdata = [];
        const goodsdatalog = [];
        const cikadata = [];
        const kaxiangdatalog = [];
        const zancundata = [];
        const zancunadddata = [];
        for (let i = orderlist.length - 1; i >= 0; i--) {
          // 现金支付判断商品库存是否足够（先不做）先减去库存
          // 客户暂存的话库存也直接减掉，因为改产品已经属于客户，不能再出售
          if (orderlist[i].consumetype == 1) {
            // 操作库存
            if (orderlist[i].type == 1) {
              // 产品
              const goods = await this.model('or_shop_goods').db(guestModel.db()).where({goodsid: orderlist[i].typeid, shopid: shop_id}).find();
              goods.nums -= Number(orderlist[i].num);
              goodsdata.push(goods);
              goodsdatalog.push({
                departmentid: shop_id,
                goodsid: orderlist[i].typeid,
                ordertype: 'LSD',
                orderid: data.order.id,
                nums: -1 * orderlist[i].num,
                addtime: orderinfo.addtime,
                posttime: nowtime
              });
            }
            // 如果有暂存商品或项目加入到暂存表中去
            if (orderlist[i].istemp == 1) {
              zancunadddata.push({
                orderid: data.order.id,
                shopid: shop_id,
                guestid: data.order.guestid,
                goodsid: orderlist[i].typeid,
                price: orderlist[i].price,
                num: orderlist[i].num,
                nownum: orderlist[i].num,
                disprice: orderlist[i].price * orderlist[i].discount,
                amount: orderlist[i].amount,
                addtime: nowtime,
                brandid: orderlist[i].brandid,
                isgift: orderlist[i].isgift,
                isdisabled: 0
              });
            }
          }

          // 判断是否有卡信息
          if (orderlist[i].consumetype == 2) {
            // 期卡
            if (orderlist[i].cardtype == 1 && orderlist[i].endtime < nowtime) {
              await guestModel.rollback();
              return this.fail('客户期卡已经到期！不能结账！');
            }
            // 次卡
            if (orderlist[i].cardtype == 2 && orderlist[i].num > orderlist[i].nownum) {
              await guestModel.rollback();
              return this.fail('客户次卡剩余数量不足！不能结账！');
            }
            if (orderlist[i].isdisabled == 1) {
              await guestModel.rollback();
              return this.fail('有卡项已经失效！不能结账！');
            }
            const k = await this.model('or_shop_guestcardsubject').db(guestModel.db()).where({id: orderlist[i].guestcardinfoid}).find();
            // let cost = orderlist[i].cost > 0 ? orderlist[i].cost : 0
            // let amount = orderlist[i].amount * (1 - cost / 100)
            k.nownum -= Number(orderlist[i].num);
            k.amount -= orderlist[i].amount;
            k.amount = k.amount < 0 ? 0 : k.amount;
            cikadata.push(k);

            // 后期应该改成统一表，期卡里应加入消费次数
            kaxiangdatalog.push({
              departmentid: shop_id,
              guestcardid: orderlist[i].guestcardid,
              guestcardinfoid: orderlist[i].guestcardinfoid,
              num: -1 * orderlist[i].num,
              amount: -1 * orderlist[i].amount,
              addtime: nowtime,
              orderid: data.order.id,
              ordertype: 'LSD'
            });
          }

          // 操作暂存信息
          if (orderlist[i].consumetype == 3) {
            // 判断客户暂存数量是否足够（nownum问题）
            if (orderlist[i].num > orderlist[i].tnownum) {
              await guestModel.rollback();
              return this.fail('客户暂存商品剩余数量不足！不能结账！');
            }
            if (orderlist[i].goodsdisabled == 1) {
              await guestModel.rollback();
              return this.fail('该产品已经失效！不能结账！');
            }
            const z = await this.model('or_shop_guest_temp_reserve').db(guestModel.db()).where({id: orderlist[i].tempid}).find();
            z.nownum -= Number(orderlist[i].num);
            zancundata.push(z);
          }
        };

        let resgoods = 1;
        let resgoodslog = 1;
        let rescika = 1;
        let reskaxianglog = 1;
        let reszancun = 1;
        let resaddzancun = 1;

        if (zancunadddata.length > 0) {
          resaddzancun = await this.model('or_shop_guest_temp_reserve').db(guestModel.db()).addMany(zancunadddata);
        }

        if (goodsdata.length > 0) {
          resgoods = await this.model('or_shop_goods').db(guestModel.db()).updateMany(goodsdata);
          resgoodslog = await this.model('or_shop_goodslog').db(guestModel.db()).addMany(goodsdatalog);
        }

        if (cikadata.length > 0) {
          rescika = await this.model('or_shop_guestcardsubject').db(guestModel.db()).updateMany(cikadata);
        }

        if (kaxiangdatalog.length > 0) {
          reskaxianglog = await this.model('or_shop_guestcardlog').db(guestModel.db()).addMany(kaxiangdatalog);
        }

        if (zancundata.length > 0) {
          reszancun = await this.model('or_shop_guest_temp_reserve').db(guestModel.db()).updateMany(zancundata);
        }

        // 更改订单状态为1表示订单已结账
        resorder = await guestModel.where({id: data.order.id}).update(orderdata);

        // 完善预约（保留）
        // 获取今天时间戳范围
        const date = new Date();
        const btoday = Math.round(new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0).getTime() / 1000);
        const etoday = btoday + 86400;
        await this.model('bespeak').db(guestModel.db()).execute('UPDATE `think_bespeak` SET `type`=2,`arrivetime`=' + nowtime + ' WHERE  `guestid` = ' + data.order.guestid + ' and bespeaktime >= ' + btoday + ' and bespeaktime < ' + etoday);
        /* console.log(resxianjin);
        console.log(resxiaohao);
        console.log(resorder);
        console.log(resreduce);
        console.log(resginfo);
        console.log(resginfolog);
        console.log(resaccount);
        console.log(resaccountlog);
        console.log(resgoods);
        console.log(resgoodslog);
        console.log(rescika);
        console.log(reskaxianglog);
        console.log(reszancun);
        console.log(resyuyue); */
        if (resyeji && resxianjin && resorder && resreduce && resginfo && resginfolog && resaccount && resaccountlog && resgoods && resgoodslog && rescika && reskaxianglog && reszancun && resaddzancun && baseInfo) {
          await guestModel.commit();
          return this.success({data: 200, info: '结账成功'});
        } else {
          await guestModel.rollback();
          return this.fail('结账失败');
        }
      } catch (e) {
        console.log(e);
        await guestModel.rollback();
        return this.fail('结账失败');
      }
    });
  }

  /**
   * 获取订单详细信息
   * @author：黄
   */
  async getorderinfoAction() {
    const orderid = this.post('orderid');
    const orderinfo = await this.model('or_shop_order').where({id: orderid}).find();
    if (orderinfo.gendanid) {
      orderinfo.gendanname = await this.model('or_app_user').where({id: orderinfo.gendanid}).getField('name', true);
    }
    const orderlist = await this.model('or_shop_orderinfo')
      .alias('o')
      .field('o.*, c.name as cardname, if(o.tempid != 0, gr.nownum, gs.nownum) as nownum, gs.cardtype')
      .join('left join `think_or_shop_card` c on o.guestcardid = c.id')
      .join('left join `think_or_shop_guestcardsubject` gs on o.guestcardinfoid = gs.id')
      .join('left join `think_or_shop_guest_temp_reserve` gr on o.tempid = gr.id')
      .where({'o.orderid': orderid})
      .select();
    // 去除orderlist的信息
    orderlist.forEach(async row => {
      row.userTypeList = await this.model('or_shop_orderuserlist')
        .field('o.*, c.name, u.name as uname')
        .alias('o')
        .join('think_or_app_user u on o.userid = u.id')
        .join('think_or_subject_childclass c on o.classid = c.id')
        .where({'o.orderid': orderid, 'o.lineindex': row.lineindex})
        .select();
    });

    const ginfo = await this.model('or_guest')
      .alias('g')
      .field('g.*, v.vipname, v.goodsdiscount, v.subjectdiscount')
      .join('left join `think_or_guest_vipgrade` v on g.level = v.id')
      .where({'g.id': orderinfo.guestid})
      .find();

    // 获取结账和分配信息
    const accountlist = await this.model('or_shop_accountlog')
      .alias('al')
      .join('left join `think_or_shop_account` a on al.accountid = a.id')
      .where({orderid: orderid, ordertype: 'LSD'})
      .select();

    const alist = [];
    // 组合成订单表的信息
    if (accountlist.length > 0) {
      accountlist.forEach((row) => {
        alist.push({
          id: row.accountid,
          type: 1,
          accountname: row.name,
          paymoney: row.money
        });
      });
    }

    // 业绩分配
    let yejilist;
    // 根据订单状态判断，如果已经结帐，调出已经结帐的数据，如果没有结帐，调用计算窗口
    if (orderinfo.status !== 0) {
      yejilist = await this.model('or_shop_yejiticheng')
        .alias('y')
        .field('y.*, u.name,u.username')
        .join('left join `think_or_app_user` u on y.userid = u.id')
        .where({'y.ordertype': 'LSD', 'y.orderid': orderid})
        .select();
    } else {
      // 计算业绩来源
      yejilist = await this.getYeJiList(orderid);
    }

    const data = {
      orderinfo: orderinfo,
      orderlist: orderlist,
      ginfo: ginfo,
      alist: alist,
      yejilist: yejilist
    };
    return this.json(data);
  }

  /**
   * 更改业绩分配
   * @author：黄
   */
  async edityejifenpeiAction() {
    const data = JSON.parse(this.post('data'));
    // 获取订单实时信息判断状态
    const order = await this.model('or_shop_order').where({id: data.order.id}).find();
    const addtime = Math.round(new Date().getTime() / 1000);

    // 如果状态为3则不能更改业绩
    /* if (order.status == 2) {
      return this.fail('该订单已经审核不能再分配业绩！');
    } */
    if (order.status == 0) {
      return this.fail('该订单尚未结账，不能分配业绩！');
    }
    // 删除已经分配好的业绩重新分配
    const model = this.model('or_shop_yejixianjin');
    await model.transaction(async() => {
      try {
        let resyeji = 1;
        let resxianjin = 1;
        let resreduce = 1;
        let resdelxianjin = 1;
        let resdelreduce = 1;
        let resdelyeji = 1;
        let baseInfo = 1;
        let respay = 1;

        resdelxianjin = await model.where({orderid: data.order.id, feattype: 'LSD'}).delete();
        resdelreduce = await this.model('or_shop_yejicardreduce').db(model.db()).where({orderid: data.order.id, feattype: 'LSD'}).delete();
        resdelyeji = await this.model('or_shop_yejiticheng').db(model.db()).where({orderid: data.order.id, ordertype: 'LSD'}).delete();
        respay = await this.model('or_shop_userbasepay').db(model.db()).where({orderid: data.order.id, ordertype: 2}).delete();

        if (data.yejilist.length > 0) {
          const yejidata = [];
          const selluserList = [];
          const reduceuserList = [];
          const basepay = [];

          for (let i = 0; i < data.yejilist.length; i++) {
            yejidata.push({
              shopid: this.shop_userinfo.departmentid,
              orderid: data.order.id,
              ordertype: 'LSD',
              xianjinyeji: data.yejilist[i].xianjinyeji || 0,
              kahaoyeji: data.yejilist[i].kahaoyeji || 0,
              xianjinticheng: data.yejilist[i].xianjinticheng || 0,
              kahaoticheng: data.yejilist[i].kahaoticheng || 0,
              xianjinjieti: data.yejilist[i].xianjinjieti || 0,
              kahaojieti: data.yejilist[i].kahaojieti || 0,
              qitaticheng: data.yejilist[i].qitaticheng || 0,
              userid: data.yejilist[i].userid,
              bumenid: data.yejilist[i].bumenid,
              xiaozuid: data.yejilist[i].xiaozuid,
              guestid: data.order.guestid,
              addtype: data.yejilist[i].addtype || 0,
              addtime: data.order.addtime
            });
            if (data.yejilist[i].xianjinyeji > 0) {
              selluserList.push({
                orderid: data.order.id,
                feattype: 'LSD',
                shopid: this.shop_userinfo.departmentid,
                feat: data.yejilist[i].xianjinyeji,
                userid: data.yejilist[i].userid,
                bumenid: data.yejilist[i].bumenid,
                xiaozuid: data.yejilist[i].xiaozuid,
                guestid: data.order.guestid,
                addtime: data.order.addtime
              });
            }
            if (data.yejilist[i].kahaoyeji > 0) {
              reduceuserList.push({
                orderid: data.order.id,
                feattype: 'LSD',
                shopid: this.shop_userinfo.departmentid,
                feat: data.yejilist[i].kahaoyeji,
                userid: data.yejilist[i].userid,
                bumenid: data.yejilist[i].bumenid,
                xiaozuid: data.yejilist[i].xiaozuid,
                guestid: data.order.guestid,
                addtime: data.order.addtime
              });
            }
            if (data.yejilist[i].xianjinticheng > 0) {
              basepay.push({
                userid: data.yejilist[i].userid,
                category: 2,
                type: 1,
                money: data.yejilist[i].xianjinticheng,
                orderid: data.order.id,
                ordertype: 2,
                addtime: addtime,
                time: data.order.addtime
              });
            }
            if (data.yejilist[i].kahaoticheng > 0) {
              basepay.push({
                userid: data.yejilist[i].userid,
                category: 2,
                type: 3,
                money: data.yejilist[i].kahaoticheng,
                orderid: data.order.id,
                ordertype: 2,
                addtime: addtime,
                time: data.order.addtime
              });
            }
            if (data.yejilist[i].shougongticheng > 0) {
              basepay.push({
                userid: data.yejilist[i].userid,
                category: 2,
                type: 2,
                money: data.yejilist[i].shougongticheng,
                orderid: data.order.id,
                ordertype: 2,
                addtime: addtime,
                time: data.order.addtime
              });
            }
            if (data.yejilist[i].qitaticheng > 0) {
              basepay.push({
                userid: data.yejilist[i].userid,
                category: 2,
                type: 4,
                money: data.yejilist[i].qitaticheng,
                orderid: data.order.id,
                ordertype: 2,
                addtime: addtime,
                time: data.order.addtime
              });
            }
            if (data.yejilist[i].xianjinjieti > 0) {
              basepay.push({
                userid: data.yejilist[i].userid,
                category: 2,
                type: 5,
                money: data.yejilist[i].xianjinjieti,
                orderid: data.order.id,
                ordertype: 2,
                addtime: addtime,
                time: data.order.addtime
              });
            }
            if (data.yejilist[i].kahaojieti > 0) {
              basepay.push({
                userid: data.yejilist[i].userid,
                category: 2,
                type: 6,
                money: data.yejilist[i].kahaojieti,
                orderid: data.order.id,
                ordertype: 2,
                addtime: addtime,
                time: data.order.addtime
              });
            }
          }

          if (selluserList.length > 0) {
            resxianjin = await this.model('or_shop_yejixianjin').db(model.db()).addMany(selluserList);
          }
          if (reduceuserList.length > 0) {
            resreduce = await this.model('or_shop_yejicardreduce').db(model.db()).addMany(reduceuserList);
          }
          resyeji = await this.model('or_shop_yejiticheng').db(model.db()).addMany(yejidata);
          baseInfo = basepay.length > 0 ? await this.model('or_shop_userbasepay').db(model.db()).addMany(basepay) : 1;
        }
        /* console.log(resyeji);
        console.log(resxianjin);
        console.log(resreduce);
        console.log(resdelxianjin);
        console.log(resdelreduce);
        console.log(resdelyeji); */

        if (resyeji && resxianjin && resreduce && resdelxianjin !== false && resdelreduce !== false && resdelyeji !== false && baseInfo && respay !== false) {
          await model.commit();
          return this.success({data: 200, info: '编辑成功'});
        } else {
          await model.rollback();
          return this.fail('编辑失败！');
        }
      } catch (e) {
        console.log(e);
        await model.rollback();
        return this.fail('编辑失败！');
      }
    });
  }

  async fanjiezhangAction() {
    const id = this.post('id');
    // 反结账要做哪些工作
    // 首先订单表状态要改变，其次业绩表要删除三张表都要删除
    // 有使用余额或者赠送余额的删除日志，返回金额
    // 有使用现金的返回金额，删除日志
    // 商品库存日志和记录
    // 删除暂存记录
    // 有使用次卡的返还次卡次数
    // 删除卡项纪录
    // 有使用暂存，返还暂存消费

    // 判断单据是否符合状态
    const oinfo = await this.model('or_shop_order')
      .where({id: id})
      .find();

    const olist = await this.model('or_shop_orderinfo').where({orderid: id}).select();

    if (oinfo.status === 0) {
      return this.fail('该订单未结账');
    }
    // 如果
    // 默认为流水单
    const isCanEditOrder = await this.isCanEditOrder(id, 'LSD');
    if (!isCanEditOrder) {
      return this.fail('暂不允许操作其他店单据！');
    }

    // 事务开启
    const guestModel = this.model('or_shop_order');
    await guestModel.transaction(async() => {
      try {
        let resxianjin = 1;
        let resorder = 1;
        let resreduce = 1;
        let respay = 1;
        // 现金业绩表
        resxianjin = await this.model('or_shop_yejixianjin').db(guestModel.db()).where({orderid: id, feattype: 'LSD'}).delete();
        // 卡耗业绩
        resreduce = await this.model('or_shop_yejicardreduce').db(guestModel.db()).where({orderid: id, feattype: 'LSD'}).delete();

        const resyeji = await this.model('or_shop_yejiticheng').db(guestModel.db()).where({orderid: id, ordertype: 'LSD'}).delete();
        // 记得判断是否发放工资
        respay = await this.model('or_shop_userbasepay').db(guestModel.db()).where({orderid: id, ordertype: 2}).delete();

        const orderdata = {
          status: 0,
          auditorid: 0,
          gendanid: 0
        };
        let resdelbalancelog = 1;
        let resbalance = 1;
        // 判断是否使用余额
        if (oinfo.usebalance != 0 || oinfo.usegiftbalance != 0) {
          // 删除日志，返回金额
          resdelbalancelog = await this.model('or_shop_guest_accountlog').db(guestModel.db()).where({ordertype: 'LSD', orderid: id}).delete();
          // 取金额
          const ginfo = await this.model('or_guest').db(guestModel.db()).where({id: oinfo.guestid}).find();
          resbalance = await this.model('or_guest').db(guestModel.db()).where({id: oinfo.guestid}).update({
            balance: ginfo.balance + Number(oinfo.usebalance),
            giftbalance: ginfo.giftbalance + Number(oinfo.usegiftbalance)
          });
        }

        // 如果有普通收款，删除日志，返还金额
        let resaccount = 1;
        let resaccountlog = 1;
        if (oinfo.recemoney > 0) {
          const accountlog = await this.model('or_shop_accountlog').db(guestModel.db()).where({ordertype: 'LSD', orderid: id}).select();
          const accountdata = [];
          for (var i = accountlog.length - 1; i >= 0; i--) {
            const account = await this.model('or_shop_account').db(guestModel.db()).where({id: accountlog[i].accountid}).find();
            account.balance -= Number(accountlog[i].money);
            accountdata.push(account);
          }
          resaccount = await this.model('or_shop_account').db(guestModel.db()).updateMany(accountdata);
          resaccountlog = await this.model('or_shop_accountlog').db(guestModel.db()).where({ordertype: 'LSD', orderid: id}).delete();
        }

        // 判断是否有商品
        const goodslog = await this.model('or_shop_goodslog').db(guestModel.db()).where({ordertype: 'LSD', orderid: id}).select();
        let resgoods = 1;
        let resgoodslog = 1;
        const goodsdata = [];
        if (goodslog.length > 0) {
          for (let i = goodslog.length - 1; i >= 0; i--) {
            const goods = await this.model('or_shop_goods').db(guestModel.db()).where({goodsid: goodslog[i].goodsid, shopid: this.shop_userinfo.departmentid}).find();
            goods.nums -= Number(goodslog[i].nums);
            goodsdata.push(goods);
          }
          resgoods = await this.model('or_shop_goods').db(guestModel.db()).updateMany(goodsdata);
          resgoodslog = await this.model('or_shop_goodslog').db(guestModel.db()).where({ordertype: 'LSD', orderid: id}).delete();
        }

        // 如果有暂存的话，删除暂存的商品
        const reszancun = await this.model('or_shop_guest_temp_reserve').db(guestModel.db()).where({orderid: id, shopid: this.shop_userinfo.departmentid}).delete();

        // 如果有卡项消费，删除消费日志，返还次卡次数和金额
        const guestcardlog = await this.model('or_shop_guestcardlog').db(guestModel.db()).where({orderid: id, ordertype: 'LSD'}).select();
        let resguestcard = 1;
        let resguestcardlog = 1;
        if (guestcardlog.length > 0) {
          const guestcardsubjectdata = [];
          for (var i = guestcardlog.length - 1; i >= 0; i--) {
            const guestcardsubject = await this.model('or_shop_guestcardsubject').db(guestModel.db()).where({id: guestcardlog[i].guestcardinfoid}).find();
            guestcardsubject.nownum -= Number(guestcardlog[i].num);
            guestcardsubject.amount -= Number(guestcardlog[i].amount);
            guestcardsubjectdata.push(guestcardsubject);
          }
          resguestcard = await this.model('or_shop_guestcardsubject').db(guestModel.db()).updateMany(guestcardsubjectdata);
          resguestcardlog = await this.model('or_shop_guestcardlog').db(guestModel.db()).where({orderid: id, ordertype: 'LSD'}).delete();
        }

        // 因为暂存目前没有日志表，所以只能从订单表中取
        let restemp = 1;
        const tempdata = [];
        for (let i = olist.length - 1; i >= 0; i--) {
          if (olist[i].consumetype == 3) {
            const temp = await this.model('or_shop_guest_temp_reserve').db(guestModel.db()).where({id: olist[i].tempid}).find();
            temp.nownum += Number(olist[i].num);
            tempdata.push(temp);
          }
        }

        if (tempdata.length > 0) {
          restemp = await this.model('or_shop_guest_temp_reserve').db(guestModel.db()).updateMany(tempdata);
        }

        // 更改订单状态为1表示订单已结账
        resorder = await guestModel.where({id: id}).update(orderdata);

        // 完善预约（保留）
        // 获取今天时间戳范围
        const date = new Date();
        const btoday = Math.round(new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0).getTime() / 1000);
        const etoday = btoday + 86400;
        await this.model('bespeak').db(guestModel.db()).execute('UPDATE `think_bespeak` SET `type`=1,`arrivetime`=0 WHERE  `guestid` = ' + oinfo.guestid + ' and bespeaktime >= ' + btoday + ' and bespeaktime < ' + etoday);

        /* console.log(resyeji)
            console.log(resxianjin)
            console.log(resorder)
            console.log(resreduce)
            console.log(resdelbalancelog)
            console.log(resbalance)
            console.log(resaccount)
            console.log(resaccountlog)
            console.log(resgoods)
            console.log(resgoodslog)
            console.log(reszancun)
            console.log(resguestcard)
            console.log(resguestcardlog)
            console.log(restemp)
            console.log(resyuyue) */

        if (resyeji !== false && resxianjin !== false && resorder && resreduce !== false && resdelbalancelog && resbalance && resaccount && resaccountlog && resgoods && resgoodslog && resguestcard && resguestcardlog && reszancun !== false && restemp && respay !== false) {
          await guestModel.commit();
          return this.success({data: 200, info: '反结账成功'});
        } else {
          await guestModel.rollback();
          return this.fail('反结账失败');
        }
      } catch (e) {
        await guestModel.rollback();
        console.log(e);
        return this.fail('反结账失败');
      }
    });
  }

  async getYeJiList(id) {
    // 获取订单信息
    const fenList = await this.model('or_shop_orderuserlist')
      .alias('ou')
      .join('think_or_shop_orderinfo o on ou.orderid = o.orderid and ou.lineindex = o.lineindex')
      .join('think_or_app_user u on ou.userid = u.id')
      .where({'ou.orderid': id})
      .select();
    const list = [];
    // 取数据
    for (let i = 0; i < fenList.length; i++) {
      // 获取分项的提成类型
      // 计算该行产生的现金和卡耗
      let xianjin = fenList[i].usemoney;
      let kahao = fenList[i].usebalance + fenList[i].usegiftbalance + fenList[i].usecard;
      // 计算该行按比例应得的现金和卡耗
      xianjin = xianjin * fenList[i].percent;
      kahao = kahao * fenList[i].percent;
      // 根据设置比例计算最后的业绩和提成
      const tichengtype = await this.model('or_subject_config').where({departmentid: this.shop_userinfo.departmentid, type: fenList[i].type, subjectid: fenList[i].typeid, subjectchildclassid: fenList[i].classid}).find();
      const xianjinticheng = tichengtype.xjtctype === 1 ? ((tichengtype.xjtcpercent * xianjin) / 100).toFixed(2) : tichengtype.xjtcfixed;
      const kahaoticheng = tichengtype.khtctype === 1 ? ((tichengtype.khtcpercent * kahao) / 100).toFixed(2) : tichengtype.khtcfixed;
      const xianjinyeji = ((tichengtype.xjyjpercent * xianjin) / 100).toFixed(2);
      const kahaoyeji = ((tichengtype.khyjpercent * kahao) / 100).toFixed(2);

      // 合并重复
      const key = this.inArray(fenList[i].userid, list);
      if (key > -1) {
        list[key] = {
          userid: fenList[i].userid,
          bumenid: fenList[i].bumenid,
          xiaozuid: fenList[i].xiaozuid,
          name: fenList[i].name,
          xianjinticheng: (Number(xianjinticheng) + Number(list[key].xianjinticheng)).toFixed(2),
          kahaoticheng: (Number(kahaoticheng) + Number(list[key].kahaoticheng)).toFixed(2),
          xianjinyeji: (Number(xianjinyeji) + Number(list[key].xianjinyeji)).toFixed(2),
          kahaoyeji: (Number(kahaoyeji) + Number(list[key].kahaoyeji)).toFixed(2),
          qitaticheng: 0,
          typename: fenList[i].typename
        };
      } else {
        list.push({
          userid: fenList[i].userid,
          bumenid: fenList[i].bumenid,
          xiaozuid: fenList[i].xiaozuid,
          name: fenList[i].name,
          xianjinticheng: xianjinticheng,
          kahaoticheng: kahaoticheng,
          xianjinyeji: xianjinyeji,
          kahaoyeji: kahaoyeji,
          qitaticheng: 0,
          typename: fenList[i].typename
        });
      }
    }
    // 查询是否开通了阶梯提成
    const baseConfig = await this.model('or_shop_basis').where({shopid: this.shop_userinfo.departmentid}).find();
    const order = await this.model('or_shop_order').where({id: id}).find();
    const dates = new Date(order.addtime * 1000);
    const beginToday = dates.setHours(0, 0, 0, 0) / 1000;
    const beginMonth = new Date(dates.getFullYear(), dates.getMonth()).getTime() / 1000;
    const beginYear = new Date(dates.getFullYear(), 0).getTime() / 1000;

    if (list.length > 0 && order.status !== 2) {
      for (let i = list.length - 1; i >= 0; i--) {
        list[i].xianjinjieti = 0;
        list[i].xianjinxinxi = [];
        list[i].kahaojieti = 0;
        list[i].kahaoxinxi = [];
        if (baseConfig && baseConfig.isticheng) {
        // 取本月开始时间戳
          list[i].userfeat = await this.model('or_shop_yejiticheng').field('sum(if(addtime > ' + beginToday + ', xianjinyeji, 0)) as todayxj, sum(if(addtime > ' + beginToday + ', kahaoyeji, 0)) as todaykh, sum(if(addtime > ' + beginMonth + ', xianjinyeji, 0)) as monthxj, sum(if(addtime > ' + beginMonth + ', kahaoyeji, 0)) as monthkh,sum(if(addtime > ' + beginYear + ', xianjinyeji, 0)) as yearxj, sum(if(addtime > ' + beginYear + ', kahaoyeji, 0)) as yearkh').where({userid: list[i].userid, addtime: {'>=': beginYear, '<=': order.addtime}}).find();
          // 取出配置
          const cf = JSON.parse(baseConfig.tichengarr || '[]');
          if (cf.length) {
            for (let m = 0; m < cf.length; m++) {
              switch (cf[m].timetype) {
                case 1:
                  if (cf[m].feattype == 1) {
                    if (cf[m].feet <= list[i].userfeat.yearxj) {
                    // console.log(1)
                      list[i].xianjinjieti += list[i].xianjinyeji * cf[m].percent / 100;
                      list[i].xianjinxinxi.push(list[i].name + '年度现金业绩为' + list[i].userfeat.yearxj + '元，获得年度现金业绩大于' + cf[m].feet + '的额外' + cf[m].percent + '个点的提成' + list[i].xianjinyeji * cf[m].percent / 100 + '元');
                    }
                  } else {
                    if (cf[m].feet <= list[i].userfeat.yearkh) {
                    // console.log(1)
                      list[i].kahaojieti += list[i].kahaoyeji * cf[m].percent / 100;
                      list[i].kahaoxinxi.push(list[i].name + '年度卡耗业绩为' + list[i].userfeat.yearkh + '元，获得年度卡耗业绩大于' + cf[m].feet + '的额外' + cf[m].percent + '个点的提成' + list[i].kahaoyeji * cf[m].percent / 100 + '元');
                    }
                  }

                  break;
                case 2:
                  if (cf[m].feattype == 1) {
                    if (cf[m].feet <= list[i].userfeat.monthxj) {
                    // console.log(2)
                      list[i].xianjinjieti += list[i].xianjinyeji * cf[m].percent / 100;
                      list[i].xianjinxinxi.push(list[i].name + '月度现金业绩为' + list[i].userfeat.monthxj + '元，获得月度现金业绩大于' + cf[m].feet + '的额外' + cf[m].percent + '个点的提成' + list[i].xianjinyeji * cf[m].percent / 100 + '元');
                    }
                  } else {
                    if (cf[m].feet <= list[i].userfeat.monthkh) {
                    // console.log(2)
                      list[i].kahaojieti += list[i].kahaoyeji * cf[m].percent / 100;
                      list[i].kahaoxinxi.push(list[i].name + '月度卡耗业绩为' + list[i].userfeat.monthkh + '元，获得月度卡耗业绩大于' + cf[m].feet + '的额外' + cf[m].percent + '个点的提成' + list[i].kahaoyeji * cf[m].percent / 100 + '元');
                    }
                  }

                  break;
                case 3:
                  if (cf[m].feattype == 1) {
                    if (cf[m].feet <= list[i].userfeat.todayxj) {
                    // console.log(3)
                      list[i].xianjinjieti += list[i].xianjinyeji * cf[m].percent / 100;
                      list[i].xianjinxinxi.push(list[i].name + '当日现金业绩为' + list[i].userfeat.todayxj + '元，获得当日现金业绩大于' + cf[m].feet + '的额外' + cf[m].percent + '个点的提成' + list[i].xianjinyeji * cf[m].percent / 100 + '元');
                    }
                  } else {
                    if (cf[m].feet <= list[i].userfeat.todaykh) {
                    // console.log(3)
                      list[i].kahaojieti += list[i].kahaoyeji * cf[m].percent / 100;
                      list[i].kahaoxinxi.push(list[i].name + '当日卡耗业绩为' + list[i].userfeat.todaykh + '元，获得当日卡耗业绩大于' + cf[m].feet + '的额外' + cf[m].percent + '个点的提成' + list[i].kahaoyeji * cf[m].percent / 100 + '元');
                    }
                  }
                  break;
              }
            }
          }
        }
        list[i].xianjinjieti = list[i].xianjinjieti.toFixed(2);
        list[i].kahaojieti = list[i].kahaojieti.toFixed(2);
      }
    }
    return list;
  }

  inArray(item, list) {
    let key = -1;
    list.forEach((row, index) => {
      if (row.userid === item) {
        key = index;
      }
    });
    return key;
  }
}
